package org.xwalk.core.internal;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class XWalkHttpAuthHandlerBridge extends XWalkHttpAuthHandlerInternal {
    private XWalkCoreBridge coreBridge;
    private Object wrapper;

    public Object getWrapper() {
        return wrapper;
    }


    private XWalkHttpAuthHandlerInternal internal;

    XWalkHttpAuthHandlerBridge(XWalkHttpAuthHandlerInternal internal) {
        this.internal = internal;
        reflectionInit();
    }

    @Override
    public void proceed(String username, String password) {
        if (proceedStringStringMethod == null || proceedStringStringMethod.isNull()) {
            proceedSuper(username, password);
        } else {
            proceedStringStringMethod.invoke(username, password);
        }
    }

    public void proceedSuper(String username, String password) {
        if (internal == null) {
            super.proceed(username, password);
        } else {
            internal.proceed(username, password);
        }
    }

    private ReflectMethod proceedStringStringMethod = new ReflectMethod(null, "proceed");

    @Override
    public void cancel() {
        if (cancelMethod == null || cancelMethod.isNull()) {
            cancelSuper();
        } else {
            cancelMethod.invoke();
        }
    }

    public void cancelSuper() {
        if (internal == null) {
            super.cancel();
        } else {
            internal.cancel();
        }
    }

    private ReflectMethod cancelMethod = new ReflectMethod(null, "cancel");

    @Override
    public boolean isFirstAttempt() {
        if (isFirstAttemptMethod == null || isFirstAttemptMethod.isNull()) {
            return isFirstAttemptSuper();
        } else {
            return (Boolean)isFirstAttemptMethod.invoke();
        }
    }

    public boolean isFirstAttemptSuper() {
        boolean ret;
        if (internal == null) {
            ret = super.isFirstAttempt();
        } else {
            ret = internal.isFirstAttempt();
        }
        
        return ret;
    }

    private ReflectMethod isFirstAttemptMethod = new ReflectMethod(null, "isFirstAttempt");


    void reflectionInit() {
        coreBridge = XWalkCoreBridge.getInstance();
        if (coreBridge == null) return;

        ReflectConstructor constructor = new ReflectConstructor(
                coreBridge.getWrapperClass("XWalkHttpAuthHandler"), Object.class);
        try {
            wrapper = constructor.newInstance(this);
        } catch (UnsupportedOperationException e) {
            return;
        }

        proceedStringStringMethod.init(wrapper, null,
                "proceed", String.class, String.class);
        cancelMethod.init(wrapper, null,
                "cancel");
        isFirstAttemptMethod.init(wrapper, null,
                "isFirstAttempt");
    }
}
